﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Xml;

namespace Egora.Pvp
{
  public class PvpToken :PvpValueBase
  {
    private PvpAuthentication _authentication = new PvpAuthentication();
    private PvpAuthorization _authorization;

    public PvpToken()
    {
    }

    public PvpToken(NameValueCollection values):base(values)
    {
      _authentication = new PvpAuthentication(values);
      _authorization = new PvpAuthorization(values);
    }

    public string X_AUTHENTICATE_participantId
    {
      get { return GetValue(PvpIdentifier.X_AUTHENTICATE_participantId ); }
      set { SetValue(PvpIdentifier.X_AUTHENTICATE_participantId, value); }
    }
    public string X_Version
    {
      get { return GetValue(PvpIdentifier.X_Version); }
      set { SetValue(PvpIdentifier.X_Version, value); }
    }
    
    public XmlElement GetChainedSoapFragment()
    {
      string pvpToken = String.Format(PvpChainedTokenFormat,
        EncodingUtil.XmlEncode(X_Version),
        EncodingUtil.XmlEncode(X_AUTHENTICATE_participantId),
        _authentication.GetSoapUserPrincipalFragment(),
        _authorization.GetSoapFragment());

      XmlDocument doc = new XmlDocument();
      doc.LoadXml(pvpToken);

      return doc.DocumentElement;;
    }

    protected string PvpChainedTokenFormat    
    {
      get
      {
        return
@"<pvpChainedToken version=""{0}"" xmlns=""http://egov.gv.at/pvp1.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<authenticate>
<participantId>{1}</participantId>
{2}
</authenticate>
<authorize>
{3}
</authorize>
</pvpChainedToken>";
      }
    }
  }
}
